package com.example.rabbitmq.consumer;

import com.example.rabbitmq.config.RabbitMQConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MessageConsumer {

    @RabbitListener(queues = RabbitMQConfig.BOOT_QUEUE)
    public void receiveMessage(String message, Channel channel, Message msg) throws IOException {
        try {
            System.out.println("接收到消息: " + message);

            // 处理业务逻辑
            processMessage(message);

            // 手动确认消息
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            System.out.println("消息处理失败: " + e.getMessage());

            // 拒绝消息并重新入队（可以根据业务需要选择是否重新入队）
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

    private void processMessage(String message) {
        // 模拟业务处理
        System.out.println("处理消息中..." + message);
    }
}
